<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发布者" prop="publisher">
        <el-input
          v-model="queryParams.publisher"
          placeholder="请输入发布者"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:pending:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pendingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="发布者" align="center" prop="publisher" />
      <el-table-column label="发布时间" align="center" prop="time" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布内容" align="center" prop="content" />
      <el-table-column label="审核状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['system:pending:query']">详情</el-button>
          <el-button 
            link 
            type="success" 
            icon="Check" 
            @click="handleAudit(scope.row)" 
            v-hasPermi="['system:pending:audit']"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠团购对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="pendingRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="发布者" prop="publisher">
          <el-input v-model="form.publisher" placeholder="请输入发布者" />
        </el-form-item>
        <el-form-item label="发布时间" prop="time">
          <el-date-picker clearable
            v-model="form.time"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预览图" prop="img">
          <el-input v-model="form.img" placeholder="请输入预览图" />
        </el-form-item>
        <el-form-item label="发布内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="咨询电话" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输入咨询电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog title="审核" v-model="auditOpen" width="500px" append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px">
                 <el-form-item label="审核结果:" prop="auditResult">
           <el-radio-group v-model="auditForm.auditResult">
             <el-radio :label="2">通过审核</el-radio>
             <el-radio :label="3">审核不通过</el-radio>
           </el-radio-group>
         </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditOpen = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Pending">
import { listPending, getPending, updatePending } from "@/api/system/pending"

const { proxy } = getCurrentInstance()

const pendingList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const auditOpen = ref(false)
const currentItem = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    publisher: null,
    status: null, // 让后端处理状态过滤
  },
  rules: {
  },
  auditForm: {
    auditResult: 2
  }
})

const { queryParams, form, rules, auditForm } = toRefs(data)

const auditRules = {
  auditResult: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ]
}

/** 查询待审核列表 */
function getList() {
  loading.value = true
  listPending(queryParams.value).then(response => {
    pendingList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    publisher: null,
    time: null,
    img: null,
    content: null,
    originalPrice: null,
    presentPrice: null,
    endTime: null,
    telephone: null,
    note: null,
    status: null,
    deleted: null
  }
  proxy.resetForm("pendingRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加优惠团购"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPending(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改优惠团购"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["pendingRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePending(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPending(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除优惠团购编号为"' + _ids + '"的数据项？').then(function() {
    return delPending(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/pending/export', {
    ...queryParams.value
  }, `pending_${new Date().getTime()}.xlsx`)
}

/** 详情按钮操作 */
function handleDetail(row) {
  // 跳转到详情页面
  proxy.$router.push(`/system/pending/detail/${row.id}`)
}

/** 审核按钮操作 */
function handleAudit(row) {
  currentItem.value = row
  auditForm.value = {
    auditResult: 2
  }
  auditOpen.value = true
}

/** 提交审核 */
function submitAudit() {
  proxy.$refs["auditFormRef"].validate(valid => {
    if (valid && currentItem.value) {
      loading.value = true
      const updateData = {
        ...currentItem.value,
        status: auditForm.value.auditResult // 4:已审核, 3:审核不通过
      }
      
      updatePending(updateData).then(response => {
        proxy.$modal.msgSuccess("审核成功")
        auditOpen.value = false
        getList()
      }).catch(() => {
        loading.value = false
        proxy.$modal.msgError("审核失败")
      })
    }
  })
}

/** 获取状态类型 */
function getStatusType(status) {
  switch (status) {
    case 0: return 'warning' // 待审核
    case 1: return 'info'    // 未上架
    case 2: return 'success' // 已通过审核
    case 3: return 'danger'  // 审核不通过
    case 5: return 'warning' // 活动已下架
    default: return 'info'
  }
}

/** 获取状态文本 */
function getStatusText(status) {
  switch (status) {
    case 0: return '待审核'
    case 1: return '未上架'
    case 2: return '已通过审核'
    case 3: return '审核不通过'
    case 5: return '活动已下架'
    default: return '未知'
  }
}

getList()
</script>
